/**
 * 函数防抖
 * @param fn 需要进行处理的函数
 * @param delay 间隔多久不发生再进行函数处理
 * @returns {Function}
 */
export function debounce(fn, delay) {
  let timerId = null;
  return function () {
    let self = this;
    let args = arguments;
    timerId && clearTimeout(timerId);
    timerId = setTimeout(function () {
      fn.apply(self, args);
    }, delay || 1000);
  }
}

/**
 * 函数节流
 * @param fn 需要进行处理的函数
 * @param delay 间隔多久执行一次函数
 * @returns {Function}
 */
export function throttle(fn, delay) {
  let timerId = null;
  let flag = true;
  return function () {
    if(!flag) return;
    flag = false;
    let self = this;
    let args = arguments;
    timerId && clearTimeout(timerId);
    timerId = setTimeout(function () {
      flag = true;
      fn.apply(self, args);
    }, delay || 1000);
  }
}

/**
 * 判断字符串占多少个字符，英文占一个，中文占两个
 * @param str 所需判断的字符串
 * @returns {*}
 */
export function getBLen(str) {
  if (str == null) return 0;
  if (typeof str != "string"){
    str += "";
  }
  return str.replace(/[^\x00-\xff]/g,"01").length;
}

/**
 * 将服务端的数据转为树形结构的数据
 * @param rawData
 */
export function tranResDataToTreeData(sNodes) {
  let i, l;
  let r = [];
  let tmpMap = {};
  for (i = 0, l = sNodes.length; i < l; i++) {
    tmpMap[sNodes[i].id] = sNodes[i];
  }
  for (i = 0, l = sNodes.length; i < l; i++) {
    let p = tmpMap[sNodes[i].parentId];
    if (p && sNodes[i].id != sNodes[i].parentId) {
      let children = nodeChildren(p);
      if (!children) {
        children = nodeChildren(p, []);
      }
      children.push(sNodes[i]);
    } else {
      r.push(sNodes[i]);
    }
  }
  return r;
}
function nodeChildren(node, newChildren) {
  if (typeof newChildren !== 'undefined') {
    node.children = newChildren;
  }
  return node.children;
}